import fs from 'fs';
import sqlite3 from "sqlite3";
import { ApiResponse, ApiResultCode, IApiRequestData, IApiResponse, IApiResponseData } from "../defines";
import logger from "../logger";

const SQL_CREATE_USERS_TABLE = `CREATE TABLE IF NOT EXISTS users (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    username TEXT UNIQUE,
    password TEXT
);`;

const SQL_CREATE_USER = `INSERT INTO users (username, password) VALUES (?, ?);`;
const SQL_GET_USER = `SELECT * FROM users WHERE username = ? AND password = ?;`;

export interface IUserDBData {
    id: number;
    username: string;
    password: string;
}

export interface IUserReqData extends IApiRequestData {
    username: string;
    password: string;
}

export interface IUserResData extends IApiResponseData {
    token: string;
}

class UserManager {

    initialized: boolean = false;

    db?: sqlite3.Database;

    constructor() {

    }

    async init() {
        logger.info('start init user manager');

        sqlite3.verbose();
        fs.mkdirSync('db', { recursive: true })

        let db = new sqlite3.Database('db/db.sqlite', (err) => {
            if (err) {
                logger.error('Could not connect to database:%s', err.message);
                return;
            }
            logger.info('connected to the SQLite database.');

            this.db = db;

            // 创建表
            db.run(SQL_CREATE_USERS_TABLE, (err) => {
                if (err) {
                    logger.error('Error creating table:%s', err.message);
                    return;
                }
            });
        });


        logger.info('init user manager done');
        this.initialized = true;
        return true;
    }

    getUser(username: string, password: string): Promise<IUserDBData | null> {
        return new Promise((resolve, reject) => {
            this.db?.get(SQL_GET_USER, [username, password], (err, row: IUserDBData) => {
                if (err) {
                    logger.error('Error getting user:%s', err.message);
                    reject(null);
                    return;
                }
                if (!row) {
                    resolve(null);
                    return;
                }

                resolve({ id: row.id, username: row.username, password: row.password });
            })
        })
    }

    createUser(username: string, password: string): Promise<IUserDBData | null> {
        return new Promise((resolve, reject) => {
            this.db?.run(SQL_CREATE_USER, [username, password], (ret: sqlite3.RunResult, err: Error | null) => {
                if (err) {
                    logger.error('Error creating user:%s', err.message);
                    reject(null);
                    return;
                }
                resolve({ id: ret.lastID, username: username, password: password });
            })
        })
    }
}



export async function login(data: IUserReqData): Promise<IApiResponse<IUserResData>> {
    const { username, password } = data;
    if (username === 'admin' && password === '123456') {
        return ApiResponse.success({ token: 'this is a token' });
    }
    return ApiResponse.fail(ApiResultCode.Unauthorized, 'Invalid credentials');
}
